/*************************************************************************
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *
 *                COPYRIGHT (C) HONGLING CAPITAL CORPORATION 2012
 *    ALL RIGHTS RESERVED BY HONGLING CAPITAL CORPORATION. THIS PROGRAM
 * MUST BE USED  SOLELY FOR THE PURPOSE FOR WHICH IT WAS FURNISHED BY
 * HONGLING CAPITAL CORPORATION. NO PART OF THIS PROGRAM MAY BE REPRODUCED
 * OR DISCLOSED TO OTHERS,IN ANY FORM, WITHOUT THE PRIOR WRITTEN
 * PERMISSION OF HONGLING CAPITAL CORPORATION. USE OF COPYRIGHT NOTICE
 DOES NOT EVIDENCE PUBLICATION OF THE PROGRAM.
 *                  HONGLING CAPITAL CONFIDENTIAL AND PROPRIETARY
 *************************************************************************/

package com.springboot.util;

import com.alibaba.fastjson.JSONObject;
import com.springboot.common.entity.BookInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * ISBN编码工具类。根据isbn（国际标准图书编号）编码获取书籍信息
 *
 * @author hongchao zhao at 2019-5-22 15:55
 */
public class ISBNUtils {

    private static Logger LOG = LoggerFactory.getLogger(ISBNUtils.class);

    enum APIType {
        DOUBAN("豆瓣图书"),
        JUHE("聚合数据"),
        ALICLOUD("阿里云"),
        ISBNDB("ISBNDB"),
        JISU("极速接口"),
        SZMESOFT("米软科技"),;
        private String type;

        APIType(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }

        public String getName() {
            return name();
        }
    }

    //豆瓣图书API，暂不支持个人使用
    public static final String DOUBAN_BOOK_ISBN_API = "https://api.douban.com/v2/book/isbn/:";
    //聚合数据API，收费，约两分钱一次
    public static final String JUHE_BOOK_ISBN_API = "http://feedback.api.juhe.cn/ISBN";
    //聚合数据请求appKey
    public static final String JUHE_BOOK_ISBN_API_KEY = "d1c74ab0b18f7ff6fb1a3c4de144400a";

    //阿里云API，收费，1元30次
    public static final String ALICLOUD_BOOK_ISBN_API = "https://isbn.market.alicloudapi.com/ISBN";
    //isbndb外国接口，收费
    public static final String ISBNDB_BOOK_ISBN_API = "https://api2.isbndb.com/book/";
    //极速接口，收费，1元100次
    public static final String JISU_BOOK_ISBN_API = "https://api.jisuapi.com/isbn/query";
    //极速数据请求appKey
    public static final String JISU_BOOK_ISBN_KEY = "a0d99350117d2ed5";

    //米软科技接口，目前免费
    public static final String SZMESOFT_BOOK_ISBN_API = "http://isbn.szmesoft.com/isbn/query?isbn=";


    /**
     * 根据ISBN编号获取图书信息。
     * <p>
     * 图片：http://isbn.szmesoft.com/ISBN/GetBookPhoto?ID=PhotoUrl
     * </p>
     *
     * @param isbn 国际标准图书编号。
     * @return 图书信息。
     */
    public static BookInfo getBookInfoFromSzMeSoft(String isbn) {
        String url = SZMESOFT_BOOK_ISBN_API + isbn;
        try {
            String result = HttpUtils.doGet(url, null);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String errorCode = jsonObject.getString("ErrorCode");
            if (StringUtils.isBlank(errorCode)) {
                BookInfo bookInfo = new BookInfo();
                bookInfo.setIsbn13(jsonObject.getString("ISBN"));
                bookInfo.setTitle(jsonObject.getString("BookName"));
                bookInfo.setAuthor(jsonObject.getString("Author"));
                bookInfo.setPublisher(jsonObject.getString("Publishing"));
                bookInfo.setPages(jsonObject.getString("Pages"));
                bookInfo.setPrice(jsonObject.getString("Price"));
                bookInfo.setImagesMedium("http://isbn.szmesoft.com/ISBN/GetBookPhoto?ID=" + jsonObject.getString("PhotoUrl"));
                return bookInfo;
            } else {
                LOG.error("【米软API】获取图书信息失败：" + result);
                return null;
            }
        } catch (IOException e) {
            LOG.error("【米软API】获取图书信息异常：" + e.getMessage());
        }
        return null;
    }

    /**
     * 根据ISBN编码从聚合数据获取书籍信息。
     *
     * @param isbn 国际标准图书编号。
     * @return 图书信息。
     */
    public static BookInfo getBookInfoFromJuHe(String isbn) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("key", JUHE_BOOK_ISBN_API_KEY);
            params.put("sub", isbn);
            String result = HttpUtils.doGet(JUHE_BOOK_ISBN_API, params);
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer errorCode = jsonObject.getInteger("error_code");
            if (errorCode != null) {
                BookInfo bookInfo = new BookInfo();
                bookInfo.setLevelNum(jsonObject.getString("levelNum"));
                bookInfo.setSubtitle(jsonObject.getString("subtitle"));
                bookInfo.setAuthor(jsonObject.getString("author"));
                bookInfo.setPubdate(jsonObject.getString("pubdate"));
                bookInfo.setOriginTitle(jsonObject.getString("origin_title"));
                bookInfo.setBinding(jsonObject.getString("binding"));
                bookInfo.setPages(jsonObject.getString("pages"));
                bookInfo.setImagesMedium(jsonObject.getString("images_medium"));
                bookInfo.setImagesLarge(jsonObject.getString("images_large"));
                bookInfo.setPublisher(jsonObject.getString("publisher"));
                bookInfo.setIsbn10(jsonObject.getString("isbn10"));
                bookInfo.setIsbn13(jsonObject.getString("isbn13"));
                bookInfo.setTitle(jsonObject.getString("title"));
                bookInfo.setSummary(jsonObject.getString("summary"));
                bookInfo.setPrice(jsonObject.getString("price"));
                return bookInfo;
            } else {
                LOG.error("【聚合数据】获取图书信息失败：" + result);
                return null;
            }
        } catch (IOException e) {
            LOG.error("【聚合数据】获取图书信息异常：" + e.getMessage());
        }
        return null;
    }

    /**
     * 根据ISBN编码从极速数据获取书籍信息。
     *
     * @param isbn 国际标准图书编号。
     * @return 图书信息。
     */
    public static BookInfo getBookInfoFromJiShu(String isbn) {
        try {
            Map<String, String> params = new HashMap<>();
            params.put("appkey", JISU_BOOK_ISBN_KEY);
            params.put("isbn", isbn);
            String result = HttpUtils.doGet(JISU_BOOK_ISBN_API, params);
            JSONObject json = JSONObject.parseObject(result);
            Integer errorCode = json.getInteger("status");
            if (errorCode == 0) {
                JSONObject jsonObject = json.getJSONObject("result");
                BookInfo bookInfo = new BookInfo();
                bookInfo.setTitle(jsonObject.getString("title"));
                bookInfo.setSubtitle(jsonObject.getString("subtitle"));
                bookInfo.setImagesMedium(jsonObject.getString("pic"));
                bookInfo.setAuthor(jsonObject.getString("author"));
                bookInfo.setSummary(jsonObject.getString("summary"));
                bookInfo.setPublisher(jsonObject.getString("publisher"));
                bookInfo.setPubdate(jsonObject.getString("pubdate"));
                bookInfo.setPages(jsonObject.getString("page"));
                bookInfo.setPrice(jsonObject.getString("price"));
                bookInfo.setBinding(jsonObject.getString("binding"));
                bookInfo.setIsbn13(jsonObject.getString("isbn"));
                bookInfo.setIsbn10(jsonObject.getString("isbn10"));
                return bookInfo;
            } else {
                LOG.error("【聚合数据】获取图书信息失败：" + result);
                return null;
            }
        } catch (IOException e) {
            LOG.error("【聚合数据】获取图书信息异常：" + e.getMessage());
        }
        return null;
    }


    public static void main(String[] args) throws IOException {
        //豆瓣停止对外使用API
        BookInfo bookInfo = getBookInfoFromJiShu("9787115417305");
        System.out.println("result===>" + bookInfo);


    }
}
